package com.hyk.learning.remoting.transport.netty.server;

import com.hyk.learning.common.enums.CompressTypeEnum;
import com.hyk.learning.common.enums.RpcResponseCodeEnum;
import com.hyk.learning.common.enums.SerializationTypeEnum;
import com.hyk.learning.common.factory.SingletonFactory;
import com.hyk.learning.dto.RpcMessage;
import com.hyk.learning.dto.RpcRequest;
import com.hyk.learning.dto.RpcResponse;
import com.hyk.learning.provider.RateLimitProvider;
import com.hyk.learning.rateLimit.RateLimit;
import com.hyk.learning.remoting.constants.RpcConstants;
import com.hyk.learning.remoting.handler.RpcRequestHandler;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @className: NettyRpcServerHandler
 * @author: hyk199710
 * @description: Customize the ChannelHandler of the server to process the data sent by the client.
 * @date: 2024/5/18 21:46
 */
@Slf4j
public class NettyRpcServerHandler extends ChannelInboundHandlerAdapter {

    private final RpcRequestHandler rpcRequestHandler;

    private final RateLimitProvider rateLimitProvider;

    public NettyRpcServerHandler() {
        this.rpcRequestHandler = SingletonFactory.getInstance(RpcRequestHandler.class);
        this.rateLimitProvider = SingletonFactory.getInstance(RateLimitProvider.class);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            if (msg instanceof RpcMessage) {
                log.info("server receive msg: [{}]", msg);
                byte messageType = ((RpcMessage) msg).getMessageType();
                RpcMessage rpcMessage = new RpcMessage();
                rpcMessage.setCodec(SerializationTypeEnum.HESSIAN.getCode());
                rpcMessage.setCompress(CompressTypeEnum.GZIP.getCode());
                if (messageType == RpcConstants.HEARTBEAT_REQUEST_TYPE) {
                    rpcMessage.setMessageType(RpcConstants.HEARTBEAT_RESPONSE_TYPE);
                    rpcMessage.setData(RpcConstants.PONG);
                } else {
                    RpcRequest rpcRequest = (RpcRequest) ((RpcMessage) msg).getData();
                    RateLimit rateLimit = this.rateLimitProvider.getRateLimit(rpcRequest.getRpcServiceName());
                    if(!rateLimit.getToken()){
                        RpcResponse<Object> rpcResponse = RpcResponse.fail(RpcResponseCodeEnum.FAIL);
                        rpcMessage.setData(rpcResponse);
                        log.error("Service {} got token failed", rpcRequest.getRpcServiceName());
                    }
                    else{
                        // Execute the target method (the method the client needs to execute) and return the method result
                        Object result = rpcRequestHandler.handle(rpcRequest);
                        log.info(String.format("server get result: %s", result.toString()));
                        rpcMessage.setMessageType(RpcConstants.RESPONSE_TYPE);
                        if (ctx.channel().isActive() && ctx.channel().isWritable()) {
                            RpcResponse<Object> rpcResponse = RpcResponse.success(result, rpcRequest.getRequestId());
                            rpcMessage.setData(rpcResponse);
                        } else {
                            RpcResponse<Object> rpcResponse = RpcResponse.fail(RpcResponseCodeEnum.FAIL);
                            rpcMessage.setData(rpcResponse);
                            log.error("not writable now, message dropped");
                        }
                    }
                }
                ctx.writeAndFlush(rpcMessage).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            }
        } finally {
            //Ensure that ByteBuf is released, otherwise there may be memory leaks
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (IdleState.READER_IDLE == state) {
                log.info("idle check happen, so close the connection");
                ctx.close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("server catch exception");
        cause.printStackTrace();
        ctx.close();
    }
}
